//
//  NetworkManager.m
//  ai2ban
//
//  Created by Heartbeats on 2018/1/21.
//  Copyright © 2018年 mac book pro. All rights reserved.
//

#import "NetworkManager.h"
#import <AFNetworking/AFHTTPSessionManager.h>

@interface NetworkManager()

@end

@implementation NetworkManager

+ (instancetype) shareNetwork {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL: [NSURL URLWithString:BaseUrl]];
        
    });
    return instance;
}

- (void)requestWithURLString: (NSString *)URLString
                  parameters: (NSDictionary *)parameters
                      method: (NSString *)method
                    callBack: (void (^)(id))callBack {
    
    self.responseSerializer = [AFJSONResponseSerializer serializer];    
    [self.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Accept"];
    
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    if ([method isEqualToString:@""]) {
        method = @"GET";
    }
    if ([method isEqualToString:@"GET"]) {
        [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            callBack(nil);
        }];
    }
    
    if ([method isEqualToString:@"POST"]) {
        [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            callBack(nil);
        }];
    }
}

- (void) uploadImageFile:(NSData *)imageData fileName:(NSString *)fileName url:(NSString *)ulr  callBack: (void (^)(id))callBack{
    [self POST:ulr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"advert_file" fileName:fileName mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        callBack(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

@end
